<template>
  <div class="rank-page">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="container">
        <div class="logo">
          <h1>番茄读书</h1>
        </div>
        <nav class="nav">
          <ul>
            <li><span @click="goToHome">首页</span></li>
            <li><span @click="goToBookshelf">书架</span></li>
            <li><span class="active">排行</span></li>
            <li><span @click="goToLibrary">书库</span></li>
          </ul>
        </nav>
        <div class="search-box">
          <input 
            type="text" 
            placeholder="搜索小说" 
            v-model="searchQuery"
            @keyup.enter="performSearch"
          >
          <button @click="performSearch">搜索</button>
        </div>
        <div class="user-actions" v-if="!isLoggedIn">
          <router-link to="/login" class="login-btn">登录</router-link>
          <router-link to="/login" class="register-btn">注册</router-link>
        </div>
        <div class="user-actions" v-else>
          <span class="welcome">欢迎, {{ user.name }}!</span>
          <button class="logout-btn" @click="logout">退出登录</button>
        </div>
      </div>
    </header>

    <!-- 排行内容区域 -->
    <section class="rank-content">
      <div class="container">
        <div class="section-header">
          <h2>番茄巅峰榜</h2>
          <div class="header-actions">
            <span class="book-count" v-if="rankedBooks.length > 0">共 {{ rankedBooks.length }} 本</span>
          </div>
        </div>
        
        <div class="rank-tabs">
          <div 
            class="tab" 
            :class="{ active: activeTab === 'all' }"
            @click="setActiveTab('all')"
          >
            综合排行
          </div>
          <div 
            class="tab" 
            :class="{ active: activeTab === 'monthly' }"
            @click="setActiveTab('monthly')"
          >
            月度排行
          </div>
          <div 
            class="tab" 
            :class="{ active: activeTab === 'weekly' }"
            @click="setActiveTab('weekly')"
          >
            周排行
          </div>
        </div>
        
        <div class="books-container">
          <div class="book-card" v-for="(book, index) in displayedBooks" :key="book.id" @click="goToBookDetail(book.id)">
            <div class="rank-badge" :class="{ 'top-three': index < 3 }">{{ index + 1 }}</div>
            <div class="book-cover">
              <img :src="book.image || defaultCover" :alt="book.title" @error="handleImageError">
            </div>
            <div class="book-info">
              <h3 class="book-title">{{ book.title }}</h3>
              <p class="book-author">{{ book.author || '未知作者' }}</p>
              <p class="book-stats">
                <span class="stats-item">
                  <i class="icon-fire"></i> 热度 {{ formatCount(getBookPopularity(book)) }}
                </span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 底部 -->
    <footer class="footer">
      <div class="container">
        <div class="footer-content">
          <div class="footer-section">
            <h3>关于我们</h3>
            <ul>
              <li><span>关于我们</span></li>
              <li><span>联系我们</span></li>
              <li><span>加入我们</span></li>
            </ul>
          </div>
          <div class="footer-section">
            <h3>服务支持</h3>
            <ul>
              <li><span>帮助中心</span></li>
              <li><span>反馈建议</span></li>
              <li><span>网站地图</span></li>
            </ul>
          </div>
          <div class="footer-section">
            <h3>下载APP</h3>
            <div class="qr-code">
              <div class="qr-placeholder"></div>
              <p>扫码下载番茄小说APP</p>
            </div>
          </div>
        </div>
        <div class="copyright">
          <p>© 2025 番茄小说网 版权所有</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
export default {
  name: 'Rank',
  data() {
    return {
      rankedBooks: [],
      displayedBooks: [],
      activeTab: 'all',
      searchQuery: '',
      isLoggedIn: false,
      user: null,
      defaultCover: new URL('@/assets/default-cover.jpg', import.meta.url).href
    }
  },
  methods: {
    async fetchBooks() {
      try {
        const response = await fetch('/api/fanqie/list');
        const result = await response.json();
        
        if (result.success && result.data) {
          // 为每本书生成一个随机热度值并排序
          this.rankedBooks = result.data.map(book => ({
            ...book,
            // 为每本书生成一个随机热度值
            popularity: Math.floor(Math.random() * 1000000)
          })).sort((a, b) => {
            // 根据热度值降序排列
            return b.popularity - a.popularity;
          });
          
          this.displayedBooks = [...this.rankedBooks];
        }
      } catch (error) {
        console.error('获取排行数据失败:', error);
      }
    },
    getBookPopularity(book) {
      // 获取书籍的热度值，如果不存在则返回0
      return book.popularity || 0;
    },
    formatCount(num) {
      if (num >= 100000000) {
        return (num / 100000000).toFixed(1) + '亿';
      } else if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
      }
      return num.toString();
    },
    setActiveTab(tab) {
      this.activeTab = tab;
      // 根据不同的tab显示不同的排行数据
      // 每次切换tab时重新获取数据并生成新的热度值
      this.fetchBooks();
    },
    async performSearch() {
      if (!this.searchQuery.trim()) {
        alert('请输入搜索关键词');
        return;
      }
      
      // 跳转到首页并传递搜索关键词
      this.$router.push({
        path: '/',
        query: { q: this.searchQuery }
      });
    },
    logout() {
      // 清除本地存储的用户信息
      localStorage.removeItem('user');
      localStorage.removeItem('token');
      delete window.Authorization;
      
      // 更新登录状态
      this.isLoggedIn = false;
      this.user = null;
      
      // 跳转到登录页面
      this.$router.push('/login');
    },
    handleImageError(event) {
      // 当图片加载失败时，使用默认封面
      event.target.src = this.defaultCover;
    },
    goToBookDetail(bookId) {
      // 跳转到书籍详情页面
      this.$router.push(`/book/${bookId}`);
    },
    goToHome() {
      // 跳转到首页
      this.$router.push('/');
    },
    goToBookshelf() {
      // 跳转到书架页面
      this.$router.push('/bookshelf');
    },
    goToLibrary() {
      // 跳转到书库页面
      this.$router.push('/library');
    }
  },
  mounted() {
    // 检查用户是否已登录
    const userString = localStorage.getItem('user');
    const token = localStorage.getItem('token');
    
    if (userString && token) {
      try {
        this.user = JSON.parse(userString);
        this.isLoggedIn = true;
        window.Authorization = `Bearer ${token}`;
      } catch (e) {
        console.error('解析用户信息失败:', e);
        // 如果解析失败，清除本地存储
        localStorage.removeItem('user');
        localStorage.removeItem('token');
      }
    }
    
    // 获取排行数据
    this.fetchBooks();
  }
}
</script>

<style scoped>
.rank-page {
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: #f5f5f5;
  color: #333;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 顶部导航栏样式 */
.header {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header .container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.logo h1 {
  color: #ff6633;
  margin: 0;
  font-size: 24px;
}

.nav ul {
  display: flex;
  list-style: none;
}

.nav li {
  margin: 0 15px;
}

.nav a,
.nav span {
  color: #666;
  font-size: 16px;
  transition: color 0.3s;
  cursor: pointer;
  text-decoration: none;
  outline: none;
  border: none;
}

.nav a:hover,
.nav a:focus,
.nav a:active,
.nav a.active,
.nav span:hover,
.nav span:focus,
.nav span:active,
.nav span.active {
  color: #ff6633;
  outline: none;
  border: none;
}

.search-box {
  display: flex;
}

.search-box input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  width: 200px;
}

.search-box button {
  background-color: #ff6633;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  padding: 8px 15px;
  cursor: pointer;
}

.user-actions a {
  text-decoration: none;
  display: inline-block;
  margin-left: 10px;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  text-align: center;
  transition: all 0.3s;
}

.login-btn {
  background-color: transparent;
  color: #ff6633;
  border: 1px solid #ff6633;
}

.login-btn:hover {
  background-color: #ff6633;
  color: white;
}

.register-btn {
  background-color: #ff6633;
  color: white;
  border: 1px solid #ff6633;
}

.register-btn:hover {
  background-color: #e55a2b;
  border-color: #e55a2b;
}

.welcome {
  color: #333;
  margin-right: 15px;
  font-size: 14px;
}

.logout-btn {
  background-color: #ff6633;
  color: white;
  border: 1px solid #ff6633;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.logout-btn:hover {
  background-color: #e55a2b;
  border-color: #e55a2b;
}

/* 排行内容样式 */
.rank-content {
  flex: 1;
  padding: 40px 0;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.section-header h2 {
  font-size: 28px;
  color: #333;
  margin: 0;
  position: relative;
  padding-left: 15px;
}

.section-header h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 25px;
  background: linear-gradient(to bottom, #ff6633, #ff9966);
  border-radius: 2px;
}

.book-count {
  color: #666;
  font-size: 14px;
}

.rank-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 30px;
}

.tab {
  padding: 8px 20px;
  background-color: #f5f5f5;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.tab:hover,
.tab.active {
  background-color: #ff6633;
  color: white;
}

.books-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.book-card {
  display: flex;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s;
  position: relative;
  border: 1px solid #eee;
  cursor: pointer;
}

.book-card:hover {
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
  transform: translateY(-3px);
}

.rank-badge {
  position: absolute;
  top: -8px;
  left: -8px;
  width: 24px;
  height: 24px;
  background-color: #ccc;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  z-index: 2;
}

.rank-badge.top-three {
  background: linear-gradient(to bottom, #ff9933, #ff6633);
}

.book-cover {
  width: 80px;
  height: 110px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 15px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.book-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 5px 0;
  color: #333;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.book-author {
  font-size: 13px;
  color: #999;
  margin: 0 0 10px 0;
}

.book-stats {
  display: flex;
  justify-content: space-between;
  margin: 0;
}

.stats-item {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.stats-item i {
  margin-right: 3px;
}

.icon-fire::before {
  content: "🔥";
}

/* 底部样式 */
.footer {
  background-color: #333;
  color: white;
  margin-top: 40px;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  padding: 40px 0 20px 0;
}

.footer-section {
  flex: 1;
  margin: 0 15px;
}

.footer-section h3 {
  margin: 0 0 15px 0;
  color: #ff6633;
  font-size: 18px;
  position: relative;
  padding-bottom: 10px;
}

.footer-section h3::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 30px;
  height: 2px;
  background-color: #ff6633;
}

.footer-section ul {
  list-style: none;
  padding: 0;
}

.footer-section li {
  margin: 10px 0;
}

.footer-section span {
  color: #ccc;
  transition: color 0.3s;
  cursor: pointer;
  font-size: 14px;
}

.footer-section span:hover {
  color: #ff6633;
}

.qr-code {
  text-align: center;
  padding: 10px;
}

.qr-placeholder {
  width: 120px;
  height: 120px;
  background: linear-gradient(45deg, #ff9966, #ff6633);
  border-radius: 8px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.qr-placeholder::before {
  content: "二维码";
}

.qr-code p {
  margin: 10px 0 0 0;
  font-size: 14px;
  color: #ccc;
}

.copyright {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #555;
  color: #999;
  font-size: 14px;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }
  
  .header .container {
    flex-wrap: wrap;
    height: auto;
    padding: 10px 0;
  }
  
  .nav {
    order: 3;
    width: 100%;
    margin-top: 10px;
  }
  
  .nav ul {
    justify-content: center;
  }
  
  .search-box {
    margin: 0 10px;
  }
  
  .search-box input {
    width: 120px;
  }
  
  .books-container {
    grid-template-columns: 1fr;
  }
  
  .footer-content {
    flex-direction: column;
    align-items: center;
  }
  
  .footer-section {
    margin-bottom: 20px;
    text-align: center;
  }
}
</style>